<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_quickConfigTaskList"
    :columns="columns"
    row-key="id"
    :rowSelection="rowSelection"
  >
    <!-- 配置类别 -->
    <template #configType="{ record }">
      <Tree
        v-if="record.configType.startsWith('[{')"
        :tree-data="JSON.parse(record.configType)"
      />
      <Popover
        placement="right"
        trigger="hover"
        :overlayStyle="{ width: '100px' }"
        overlayClassName="popovper-dark"
        v-else-if="record.configType.split(',').length > 2"
      >
        <template #content>
          <ul>
            <li v-for="item in record.configType.split(',')">{{ item }}</li>
          </ul>
        </template>
        <div class="truncate w-full" v-html="record.configType"></div>
      </Popover>
      <div v-else class="truncate w-full" v-html="record.configType"></div>
    </template>
    <!-- 配置推送项目 -->
    <template #projectNames="{ record }">
      <Tree
        v-if="record.projectNames && record.projectNames.length"
        :tree-data="record.projectNames"
        :field-names="fileNames"
      />
    </template>
    <template #toolbars>
      <Space>
        <b-button
          icon="add"
          @click="onAdd()"
          :code="
            pushType == '1'
              ? 'quickConfigTask:add:project'
              : 'quickConfigTask:add:device'
          "
          >新增</b-button
        >
        <b-button
          icon="delete"
          @click="onDelete()"
          :disabled="!selectKeys.length"
          :code="
            pushType == '1'
              ? 'quickConfigTask:del:project'
              : 'quickConfigTask:del:device'
          "
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="onView(record)"
        >查看</b-button
      >
      <b-button
        icon="examine"
        v-if="record.auditStatus != '1'"
        type="link"
        @click="onAudit(record)"
        :code="
          pushType == '1'
            ? 'quickConfigTask:approval:project'
            : 'quickConfigTask:approval:device'
        "
        >审核</b-button
      >
      <template v-if="pushType == '1'">
        <b-button
          type="link"
          icon="detail"
          @click="onPushDetail(record)"
          code="quickConfigTask:deviceList:project"
          >推送详情</b-button
        >
        <b-button
          type="link"
          icon="activate"
          v-if="record.auditStatus == '1' && record.status"
          @click="onEnable(record)"
          code="quickConfigTask:enable:project"
          >{{ record.status === '1' ? '停止' : '启用' }}</b-button
        >
      </template>
      <template v-else>
        <b-button
          type="link"
          icon="remote"
          v-if="record.auditStatus == '1'"
          @click="onPush(record)"
          code="quickConfigTask:configPush:device"
          >推送</b-button
        >
        <b-button
          type="link"
          icon="detail"
          v-if="record.auditStatus == '1'"
          @click="onRecord(record)"
          code="quickConfigTask:totalLog:device"
          >记录</b-button
        >
      </template>

      <b-button
        type="link"
        icon="delete"
        @click="onDelete(record.id)"
        :code="
          pushType == '1'
            ? 'quickConfigTask:del:project'
            : 'quickConfigTask:del:device'
        "
        >删除</b-button
      >
    </template>
  </ProTable>

  <FormModal2 :items="_items">
    <template #details>
      <FormItemRest>
        <div class="push_detail">
          <ProTable
            ref="listRef"
            :fetchListApi="_getList"
            :columns="_columns"
            row-key="deviceId"
            :formCol="{ md: 24, lg: 18 }"
            :btnCol="{ md: 24, lg: 6 }"
            :rowSelection="_rowSelection"
            :onValuesChange="changeFormState"
          >
            <template #toolbars>
              <Space>
                <b-button
                  icon="remote"
                  @click="onHandPush(null)"
                  :disabled="!_selectRows.length"
                  code="quickConfigTask:configPush:project"
                  >手动推送</b-button
                >
                <b-button
                  icon="detail"
                  @click="onContrast(null)"
                  :disabled="!_selectRows.length"
                  >参数对比</b-button
                >
              </Space>
            </template>
            <!-- 禅道bug编号2164 -->
            <!-- <template #operation="{ record }">
              <b-button
                type="link"
                icon="remote"
                @click="onHandPush(record)"
                v-if="record.upgradeStatus == 0"
                code="quickConfigTask:configPush:project"
                >手动推送</b-button
              >
              <b-button
                type="link"
                icon="detail"
                @click="onContrast(record)"
                v-if="record.upgradeStatus == 1 && record.compareStatus != 1"
                >参数对比</b-button
              >
            </template> -->
          </ProTable>
        </div>
      </FormItemRest>
    </template>
  </FormModal2>
  <FormModal :items="_items">
    <template #details>
      <div class="record_detail">
        <ProTable
          ref="listRef"
          :fetchListApi="_getInfo"
          :columns="_infoColumns"
          hideSearch
        >
          <template #operation="{ record }">
            <b-button type="link" icon="detail" @click="onPushDetail(record)"
              >推送详情</b-button
            >
          </template>
        </ProTable>
      </div>
    </template>
  </FormModal>

  <Modal
    v-model:open="openAudit"
    :title="auditTitle"
    :width="1200"
    :mask-closable="false"
    centered
    destroy-on-close
    wrap-class-name="config-modal"
  >
    <Audit
      ref="auditRef"
      :audit="auditInfo"
      @versionAudit="colseAudit"
      :pushType="pushType"
      key="auditRef"
      v-if="modalType === 'info' || modalType === 'audit'"
    ></Audit>
    <Add
      :configInfo="configInfo"
      :pushType="pushType"
      ref="addRef"
      key="addRef"
      @versionUpdate="pushUpdate"
      v-if="modalType === 'add' || modalType === 'edit'"
    ></Add>
    <template #footer>
      <div v-if="modalType === 'info' && auditInfo.auditStatus !== '1'">
        <b-button
          type="primary"
          @click="onEdit"
          :code="
            pushType == '1'
              ? 'quickConfigTask:update:project'
              : 'quickConfigTask:update:device'
          "
          >编 辑</b-button
        >
      </div>
      <div v-if="modalType === 'audit'">
        <b-button type="primary" @click="onAuditConfirm">通 过</b-button>
      </div>
      <div v-if="modalType === 'add' || modalType === 'edit'">
        <b-button type="primary" @click="onConfirm">提 交</b-button>
        <b-button @click="onCancel(visible)">取 消</b-button>
      </div>
    </template>
  </Modal>
  <Modal
    v-model:open="openPush"
    title="推送"
    :width="1200"
    :mask-closable="false"
    centered
    destroy-on-close
    :footer="null"
    wrap-class-name="push-modal"
  >
    <!-- ref="verifyRef" :push="pushInfo" @pushUpdate="updateLog" -->
    <Push
      :push="pushInfo"
      ref="pushRef"
      @pushUpdate="updateLog"
      @pushEnd="onPushEnd"
    ></Push>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref } from 'vue';
import CustomTree from '@/views/statistical/components/customTree.vue';
import {
  Col,
  FormItemRest,
  Modal,
  Popover,
  Radio,
  RadioButton,
  RadioGroup,
  Row,
  Select,
  Space,
  Tag,
  Tree,
  message,
} from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToOption } from '@/utils/utils';
import {
  auditStatusEnum,
  protobufVersionEnum,
  taskDeviceEnum,
  taskProjectEnum,
} from '@/constant/push';
import {
  configEnable,
  configPushLog,
  delQuickConfigTask,
  deviceCompare,
  deviceList,
  getQuickConfigTaskInfo,
  quickConfigTaskList,
  selectTotalList,
} from '@/api/push';
import { getModelInfoById } from '@/api/push';
import Add from './components/Add.vue';
import Audit from './components/Audit.vue';
import Push from './components/Push.vue';
import { pushStore } from './store';

const {
  refreshStore,
  deviceModeOptions,
  deviceModeEnum,
  getModelOptions,
  getModelEnum,
  projectList,
} = pushStore();
const init = () => {
  refreshStore.onPush();
};

init();

const pageDate: any = ref({});
const failTitle: any = ref('');
const pushDeviceData: any = ref({});
const type = ref('');
const configTabsVisible = ref(false);
const pushDeviceVisible = ref(false);
const pushConfigVisible = ref(false);
const selectKeys = ref<any[]>([]);
const rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    selectKeys.value = values;
  },
});
const tableRef = ref();
const props = defineProps({
  pushType: {
    type: String,
    default: '1',
  },
});
const pushType = ref(props.pushType); //推送方式 1-项目 2-设备

const _quickConfigTaskList = async (params: any) => {
  params.pushType = pushType.value;
  params.startTime = params.createTime?.[0];
  params.endTime = params.createTime?.[1];
  params.createTime = undefined;
  const res = await quickConfigTaskList(params);
  // 推送项目树型结构
  res.rows?.forEach((item: any) => {
    item.projectNames = [
      {
        projectName: `项目总数(${item.projectNum})`,
        children: item.projectNames?.map((project: any) => {
          return {
            projectName: project,
          };
        }),
      },
    ];
  });

  return res;
};

const fileNames = {
  title: 'projectName',
  children: 'children',
};
const currentEnum = computed(() => {
  return pushType.value === '1' ? taskProjectEnum : taskDeviceEnum;
});
const columns = computed<ProTableProps['columns']>(() =>
  [
    {
      title: '序号',
      dataIndex: 'index',
      customRender({ pageSize, pageNum, index }: any) {
        return (pageNum.value - 1) * pageSize.value + index + 1;
      },
      hideInSearch: true,
      fixed: 'left',
      width: 80,
    },
    {
      title: '配置编码ID',
      dataIndex: 'code',
      fixed: 'left',
    },
    {
      title: '协议版本',
      dataIndex: 'protobufVersion',
      valueEnum: protobufVersionEnum,
      fixed: 'left',
      customRender({ text }: any) {
        return text
          .split(',')
          .map((item: any) => protobufVersionEnum[item])
          .join();
      },
      width: 80,
    },
    {
      title: '配置类别',
      dataIndex: 'configType',
      hideInSearch: true,
      fixed: 'left',
      width: 140,
    },
    {
      title: '推送项目',
      dataIndex: 'projectNames',
      isShow: pushType.value !== '1',
      hideInSearch: true,
    },
    {
      title: '任务状态',
      dataIndex: 'status',
      valueEnum: currentEnum.value,
      hideInSearch: true,
      customRender({ text, record }: any) {
        return record.auditStatus === '0' ? (
          '--'
        ) : (
          <Tag color={text === '1' ? 'success' : 'error'}>
            {currentEnum.value[text as keyof typeof currentEnum.value]}
          </Tag>
        );
      },
      width: 80,
    },
    {
      title: '设备总数',
      dataIndex: 'deviceNum',
      hideInSearch: true,
    },
    {
      title: '成功',
      dataIndex: 'successNum',
      isShow: pushType.value !== '1',
      hideInSearch: true,
      customRender({ text, record }: any) {
        return record.auditStatus === '0' ? (
          '--'
        ) : (
          <Tag color={'success'}>{text}</Tag>
        );
      },
      width: 80,
    },
    {
      title: '失败',
      dataIndex: 'failNum',
      isShow: pushType.value !== '1',
      hideInSearch: true,
      customRender({ text, record }: any) {
        return record.auditStatus === '0' ? (
          '--'
        ) : (
          <Tag color={'error'}>{text}</Tag>
        );
      },
      width: 80,
    },
    {
      title: '等待中',
      dataIndex: 'waitNum',
      isShow: pushType.value !== '1',
      hideInSearch: true,
      customRender({ text, record }: any) {
        return record.auditStatus === '0' ? (
          '--'
        ) : (
          <Tag color={'warning'}>{text}</Tag>
        );
      },
      width: 80,
    },
    {
      title: '任务说明',
      dataIndex: 'pushDesc',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      isTime: true,
    },
    {
      title: '审核状态',
      dataIndex: 'auditStatus',
      valueEnum: auditStatusEnum,
      customRender({ text }: any) {
        const style = {
          color: text == '1' ? '#49E7BD' : '#E7A849',
        };
        return (
          <span style={style}>
            {auditStatusEnum?.[text as keyof typeof auditStatusEnum]}
          </span>
        );
      },
      width: 80,
    },

    {
      title: '审批时间',
      dataIndex: 'auditTime',
      hideInSearch: true,
      isTime: true,
    },
    {
      title: '审核人',
      dataIndex: 'auditBy',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      hideInSearch: true,
      fixed: 'right',
      width: pushType.value == '1' ? 400 : 300,
    },
  ].filter((item) => item.isShow !== true),
);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '审核结果',
    type: 'radio',
    field: 'approvalStatus',
    props: {
      options: [
        { value: 1, label: '审批通过' },
        { value: 2, label: '审批不通过' },
      ],
    },
    rules: [
      {
        required: true,
        message: `请选择审核结果`,
        trigger: 'blur',
      },
    ],
  },
]);
const { FormModal, open } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const onAdd = () => {
  modalType.value = 'add';
  openAudit.value = true;
  auditTitle.value = '新增';
  configInfo.value = {};
};

const addRef = ref();
const onConfirm = async () => {
  addRef.value.submitForm();
};

// 查看
const openAudit = ref(false);
const auditInfo = ref({});
const auditTitle = ref('');
const onAudit = async (record: any) => {
  openAudit.value = true;
  auditTitle.value = '审核';
  modalType.value = 'audit';
  getQuickConfigTaskInfo(record.id).then((res: any) => {
    if (res.data.modelAlwaysVOS) {
      res.data.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
    if (res.data.projectDeviceGroupMap) {
      res.data.projectDeviceGroupMap.forEach((item: any) => {
        if (item.modelAlwaysVOS) {
          item.modelAlwaysVOS.forEach((model: any) => {
            model.typeName = `${model.typeName}(${model.modeName.length})`;
            model.modeName = model.modeName.map((name: any) => {
              return {
                typeName: name,
              };
            });
          });
        }
      });
    }
    auditInfo.value = res.data;
  });
};
const auditRef = ref();
const onAuditConfirm = async () => {
  auditRef.value.onConfirm();
};
const colseAudit = () => {
  openAudit.value = false;
  sleep(() => tableRef.value.refresh());
};

const pushUpdate = () => {
  console.log('触发');

  tableRef.value.refresh();
  openAudit.value = false;
};

const modalType = ref('info');
const cloneInfo = ref({});
const onView = async (record: any) => {
  modalType.value = 'info';
  auditTitle.value = '查看';
  openAudit.value = true;
  getQuickConfigTaskInfo(record.id).then((res: any) => {
    console.log(res);
    if (res.data.modelAlwaysVOS) {
      res.data.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
    auditInfo.value = res.data;
    cloneInfo.value = cloneDeep(res.data);
    console.log(auditInfo.value, 'auditInfo');
  });
};
const onCancel = (visible: any) => {
  if (modalType.value === 'add') {
    openAudit.value = false;
  } else {
    modalType.value = 'info';
    auditTitle.value = '查看';
  }
  nextTick(() => {
    auditInfo.value = cloneDeep(cloneInfo.value);
  });
};
// 编辑
const configInfo = ref({});
const onEdit = async () => {
  // openAudit.value = false;
  auditTitle.value = '编辑';
  modalType.value = 'edit';
  // openAdd.value = true;
  nextTick(() => {
    configInfo.value = cloneDeep(cloneInfo.value);
  });
};

//推送
const pushInfo = ref({});
const openPush = ref(false);
const onPush = async (record: any) => {
  getQuickConfigTaskInfo(record.id).then((res: any) => {
    pushInfo.value = res.data;
  });
  nextTick(() => {
    openPush.value = true;
  });
};

const openUpdate = ref(false);
const updateInfo = ref({});
const updateLog = (data: any) => {
  updateInfo.value = data;
  openUpdate.value = true;
};

const pushSuccess = (row: any) => {
  tableRef.value.refresh();
  pushConfigVisible.value = false;
  pushDeviceData.value = row;
  failTitle.value = '推送结果';
  pushDeviceVisible.value = true;
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async (id?: number) => {
  // selectKeys.value.push(id);
  const ids = id || selectKeys.value.join(',');
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认勾选删除配置？`,
    onOk: async () => {
      await delQuickConfigTask({ ids });
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
      message.success('操作成功');
    },
  });
};

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const _items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);
const queryId = ref();
const configId = ref();
const configPushTotalId = ref();
// 推送详情
const onPushDetail = async (record: any) => {
  _selectRows.value = [];
  queryId.value = record.id;
  configPushTotalId.value = record.configPushTotalId;
  configId.value = record.configId;
  open2({
    title: '推送详情',
    modalType: 'add',
    defaultValue: { ...record },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const modListOption = ref<Record<string, any>>([]);
const changeFormState = async (params: any, formState: any) => {
  if (params.hasOwnProperty('deviceType')) {
    formState.modelId = undefined;
    if (params.deviceType) {
      const res: any = await getModelInfoById({
        type: params.deviceType,
        modelIds: '',
      });
      modListOption.value = listToOption(res.data, 'model', 'modelId');
    } else {
      modListOption.value = [];
    }
  }
};

const _getList = async (params: any) => {
  params.upgradeStatus =
    params.upgradeStatus === 'all' ? null : params.upgradeStatus;

  params.compareStatus =
    params.compareStatus === 'all' ? null : params.compareStatus;
  params.id = queryId.value || taskId.value;
  params.configPushTotalId = configPushTotalId.value;
  const res = await deviceList(params);
  return res;
};
const columnsOptions = computed(() => {
  return modListOption.value.length
    ? modListOption.value
    : getModelOptions.value;
});

const _getInfo = async (params: any) => {
  params.taskId = taskId.value;
  const res = await selectTotalList(params);
  return res;
};
const _selectRows = ref<any[]>([]);
const _rowSelection = ref<ProTableProps['rowSelection']>({
  onChange(values, selectedRows) {
    _selectRows.value = selectedRows as any[];
  },
});

const _columns = computed<ProTableProps['columns']>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    customRender({ pageSize, pageNum, index }) {
      return (pageNum.value - 1) * pageSize.value + index + 1;
    },
    hideInSearch: true,
    fixed: 'left',
    width: 80,
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    hideInSearch: true,
  },
  {
    title: '所属项目',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(formState) {
      const onChangeForTree = (value: any) => {
        formState['projectId'] = value;
      };
      return (
        <CustomTree
          filed='projectId'
          formState={formState}
          data={projectList.value}
          onChange={onChangeForTree}
        ></CustomTree>
      );
    },
  },
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    hideInSearch: true,
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    hideInSearch: true,
    valueEnum: {
      0: '离线',
      1: '在线',
    },
    customRender({ text }: any) {
      return (
        <Tag color={text == '1' ? 'success' : 'error'}>
          {text == '0' ? '离线' : '在线'}
        </Tag>
      );
    },
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: {
      ...deviceModeEnum.value,
    },
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <Select
          v-model:value={state.modelId}
          options={columnsOptions.value}
        ></Select>
      );
    },
  },
  // {
  //   title: '设备型号',
  //   dataIndex: 'modelId',
  //   valueEnum: {
  //     ...getModelEnum.value,
  //   },
  // },
  {
    title: '软件版本',
    dataIndex: 'version',
    hideInSearch: true,
    customRender({ record, text }) {
      return `${record.version || ''}${record.versionCode ? `(${record.versionCode})` : ''}`;
    },
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
    hideInSearch: true,
  },
  {
    title: '推送结果',
    dataIndex: 'upgradeStatus',
    defaultValue: 'all',
    customSearchRender(formState) {
      const option = [
        { label: '全部', value: 'all' },
        { label: '成功', value: '1' },
        { label: '失败', value: '0' },
      ];
      return (
        <RadioGroup
          options={option}
          v-model:value={formState.upgradeStatus}
        ></RadioGroup>
      );
    },
    customRender({ text }: any) {
      if (!text) return <Tag color={'processing'}>{'等待中'}</Tag>;
      return (
        <Tag color={text == '1' ? 'success' : 'error'}>
          {text == '1' ? '成功' : '失败'}
        </Tag>
      );
    },
  },
  {
    title: '参数对比',
    dataIndex: 'compareStatus',
    defaultValue: 'all',
    customRender({ text }: any) {
      if (!text) return '--';
      return (
        <Tag color={text == '1' ? 'success' : 'error'}>
          {text == '1' ? '成功' : '失败'}
        </Tag>
      );
    },
    customSearchRender(formState) {
      const option = [
        { label: '全部', value: 'all' },
        { label: '成功', value: '1' },
        { label: '失败', value: '0' },
      ];
      return (
        <RadioGroup
          options={option}
          v-model:value={formState.compareStatus}
        ></RadioGroup>
      );
    },
  },
  // {
  //   title: '操作',
  //   dataIndex: 'operation',
  //   hideInSearch: true,
  //   fixed: 'right',
  //   width: 220,
  // },
]);
const _infoColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    customRender({ pageSize, pageNum, index }) {
      return (pageNum.value - 1) * pageSize.value + index + 1;
    },
    hideInSearch: true,
    fixed: 'left',
    width: 80,
  },
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '推送人',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '本次推送总数',
    dataIndex: 'totalCount',
    hideInSearch: true,
  },
  {
    title: '成功数',
    dataIndex: 'successCount',
    hideInSearch: true,
    customRender({ text }: any) {
      return <Tag color={'success'}>{text}</Tag>;
    },
  },
  {
    title: '失败数',
    dataIndex: 'failCount',
    hideInSearch: true,
    customRender({ text }: any) {
      return <Tag color={'error'}>{text}</Tag>;
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 160,
  },
]);

const onHandPush = async (record: any) => {
  const _push = _selectRows.value.filter((i) => i.upgradeStatus == 1);
  const _online = _selectRows.value.filter((i) => i.onlineStatus != 1);
  if (_push.length) return message.error('选中设备中存在已推送成功设备!');
  if (_online.length) return message.error('选中设备中存在不在线设备!');
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: '是否确认重新推送?',
    onOk: async () => {
      const list = _selectRows.value.map((i: any) => {
        return {
          deviceId: i.deviceId,
          code: i.deviceCode,
          configId: configId.value,
          configPushTotalId: i.configPushTotalId,
          configPushId: i.configPushId,
          taskId: queryId.value,
        };
      });
      const result = await configPushLog({ list });
      if (result.code == 200) {
        sleep(() => listRef.value.refresh());
        message.success('操作成功');
      }
    },
  });
};
const listRef = ref();
const onContrast = async (record: any) => {
  const _push = _selectRows.value.filter((i) => i.upgradeStatus != 1);
  const _online = _selectRows.value.filter((i) => i.onlineStatus != 1);
  if (_push.length) return message.error('已推送成功设备才可进行参数对比!');
  if (_online.length) return message.error('选中设备中存在不在线设备!');
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: '是否确认进行参数对比?',
    onOk: async () => {
      const list = _selectRows.value.map((i: any) => {
        return {
          code: i.deviceCode,
          configId: configId.value,
          configPushId: i.configPushId,
        };
      });
      const result = await deviceCompare({ list });
      if (result.code == 200) {
        sleep(() => listRef.value.refresh());
        message.success('操作成功');
      }
    },
  });
};

//启用/停用
const onEnable = async (record: any) => {
  console.log(record.status, 'record');

  let text = record.status === 1 ? '启用' : '停止';
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认${text}当前任务?`,
    onOk: async () => {
      await configEnable({
        id: record.id,
        status: record.status == 1 ? 2 : 1,
      });
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};

const taskId = ref();
const onRecord = async (record: any) => {
  taskId.value = record.id;
  open({
    title: '推送记录',
    modalType: 'info',
    defaultValue: { ...record },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onPushEnd = () => {
  openPush.value = false;
  tableRef.value.refresh();
};
</script>

<style lang="scss">
.push_detail {
  .ant-table {
    height: calc(60vh - 300px) !important;
  }
  .ant-table-body {
    height: calc(60vh - 340px) !important;
  }
}
.record_detail {
  .ant-table {
    height: calc(60vh - 300px) !important;
  }
  .ant-table-body {
    height: calc(60vh - 340px) !important;
  }
}

.config-modal {
  .ant-modal .ant-modal-content .ant-modal-body {
    padding: 0 24px !important;
    min-height: 70vh;
  }
}
</style>
